package com.qingmeng.portal.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class GlobalCorsConfig {
    /*
    允许跨域调用的过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //SpringBoot 2.4.0 以前的版本使用addAllowedOrigin 允许所有域名进行跨域调用
        //config.addAllowedOrigin("*");
        //SpringBoot 2.4.0 之后使用addAllowedOriginPattern
        config.addAllowedOriginPattern("*");
        /*放行哪些请求方式
        * config.addAllowedMethod("GET");
        * config.addAllowedMethod("PUT");
        * config.addAllowedMethod("POST");
        * config.addAllowedMethod("DELETE");*/
        //允许跨域发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        //添加映射地址
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        //返回CorsFilter
        return new CorsFilter(source);
    }
}
